package pers.qianyu.module.image.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import pers.qianyu.module.core.domain.image.entity.ImageViewPO;
import pers.qianyu.module.core.domain.system.enums.SysUserTypeEnum;
import pers.qianyu.module.core.domain.system.vo.SimpleUserVO;
import pers.qianyu.module.image.dao.ImageViewDao;
import pers.qianyu.module.image.service.ImageViewService;
import pers.qianyu.module.system.service.SysUserService;

import java.util.Objects;

/**
 * @author mizzle rain
 * @date 2021-05-13 14:49
 */
@Service("imageViewService")
public class ImageViewServiceImpl implements ImageViewService {
    @Autowired
    private ImageViewDao imageViewDao;
    @Autowired
    private SysUserService sysUserService;

    @Async("loggingServiceExecutor")
    @Override
    public void addViewCount(Long imageId, Long userId) {
        SimpleUserVO simpleUserVO = sysUserService.querySimpleUserInfoById(userId);
        if (simpleUserVO == null || Objects.equals(simpleUserVO.getType(), SysUserTypeEnum.ADMIN_USER.getCode())) {
            return;
        }
        ImageViewPO imageViewPO = new ImageViewPO();
        imageViewPO.setImageId(imageId);
        imageViewPO.setCreatedBy(userId);
        ImageViewPO fromDb = imageViewDao.selectOne(new QueryWrapper<>(imageViewPO));
        if (fromDb != null) {
            fromDb.setCount(fromDb.getCount() + 1);
            imageViewDao.updateById(fromDb);
        } else {
            imageViewPO.setCount(1L);
            imageViewDao.insert(imageViewPO);
        }
    }
}
